<template>
  <view class="content">
    <view
      id="container"
      @touchstart="touchStart"
      @touchend="touchEnd"
      @touchmove="touchMove"
    >
      <view
        v-for="item in list"
        :key="item.id"
        :class="['box', `box_${item.id}`, { 'box-selected': item.selected }]"
        @tap="toggleSelection(item)"
      >
        <view class="box-content">
          <text class="box-number">{{ item.id }}</text>
        </view>
        <view class="selection-indicator" v-if="item.selected">✓</view>
      </view>
    </view>
    <view class="bottom-info">
      <view class="selected-info"> 已选中：{{ selectedCount }}个 </view>
      <button @click="clearSelection" class="clear-btn">清除选中</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick, getCurrentInstance, computed } from "vue";
const list = ref([]);
function init() {
  list.value = Array(30)
    .fill(0)
    .map((_, index) => ({
      id: index + 1,
      selected: false,
      clientX: 0,
      clientY: 0,
      width: 0,
      height: 0,
    }));
}
init();
const instance = getCurrentInstance();
const query = uni.createSelectorQuery().in(instance.proxy);
const selectedCount = computed(() => {
  return list.value.filter((item) => item.selected).length;
});
function getBoxInfo() {
  nextTick(() => {
    query
      .selectAll(".box")
      .boundingClientRect((data) => {
        data.forEach((rect, index) => {
          if (list.value[index]) {
            list.value[index].clientX = rect.left;
            list.value[index].clientY = rect.top;
            list.value[index].width = rect.width;
            list.value[index].height = rect.height;
          }
        });
      })
      .exec();
  });
}
getBoxInfo();
let touchClient = reactive({
  x: 0,
  y: 0,
});
let startTouchClient = reactive({
  x: 0,
  y: 0,
});
let tempSelectedItems = ref(new Set());
let selectionMode = ref(true);
let isDragging = ref(false);
function toggleSelection(item) {
  if (isDragging.value) {
    return;
  }
  item.selected = !item.selected;
  console.log(`点击切换元素 ${item.id} 状态:`, item.selected);
}
function isElementInSelection(element, startX, startY, currentX, currentY) {
  const minX = Math.min(startX, currentX);
  const maxX = Math.max(startX, currentX);
  const minY = Math.min(startY, currentY);
  const maxY = Math.max(startY, currentY);
  return (
    element.clientX < maxX &&
    element.clientX + element.width > minX &&
    element.clientY < maxY &&
    element.clientY + element.height > minY
  );
}
function determineSelectionMode(startX, startY) {
  const targetElement = list.value.find((item) => {
    return (
      startX >= item.clientX &&
      startX <= item.clientX + item.width &&
      startY >= item.clientY &&
      startY <= item.clientY + item.height
    );
  });
  if (targetElement) {
    selectionMode.value = !targetElement.selected;
  } else {
    selectionMode.value = true;
  }
}
function updateSelection() {
  tempSelectedItems.value.clear();
  list.value.forEach((item) => {
    if (touchClient.x !== 0 && touchClient.y !== 0) {
      const isInCurrentSelection = isElementInSelection(
        item,
        startTouchClient.x,
        startTouchClient.y,
        touchClient.x,
        touchClient.y
      );
      if (isInCurrentSelection) {
        tempSelectedItems.value.add(item.id);
        item.selected = selectionMode.value;
      }
    }
  });
}
function clearSelection() {
  list.value.forEach((item) => {
    item.selected = false;
  });
  tempSelectedItems.value.clear();
}
function touchStart(e) {
  touchClient.x = 0;
  touchClient.y = 0;
  startTouchClient.x = e.changedTouches[0].clientX;
  startTouchClient.y = e.changedTouches[0].clientY;
  isDragging.value = false;
  determineSelectionMode(startTouchClient.x, startTouchClient.y);
  tempSelectedItems.value.clear();
}
function touchMove(e) {
  const changedTouches = e.changedTouches[0];
  touchClient.x = changedTouches.clientX;
  touchClient.y = changedTouches.clientY;
  const moveDistance = Math.sqrt(
    Math.pow(touchClient.x - startTouchClient.x, 2) +
      Math.pow(touchClient.y - startTouchClient.y, 2)
  );
  if (moveDistance > 10) {
    isDragging.value = true;
    updateSelection();
  }
}
function touchEnd(e) {
  setTimeout(() => {
    isDragging.value = false;
  }, 100);
}
</script>

<style>
.content {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}
.header {
  text-align: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: white;
  border-radius: 10rpx;
}
.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}
.subtitle {
  font-size: 24rpx;
  color: #666;
}
#container {
  display: flex;
  flex-wrap: wrap;
  position: relative;
  padding: 20rpx;
  background-color: white;
  border-radius: 10rpx;
}
.box {
  width: 110rpx;
  height: 110rpx;
  margin: 10rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 10rpx;
  position: relative;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  cursor: pointer;
}
.box:active {
  transform: scale(0.98);
}
.box-selected {
  background: linear-gradient(135deg, #007aff 0%, #0051d5 100%) !important;
  transform: scale(0.95);
  box-shadow: 0 0 0 4rpx rgba(0, 122, 255, 0.3);
}
.box-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}
.box-number {
  color: white;
  font-size: 28rpx;
  font-weight: bold;
}
.selection-indicator {
  position: absolute;
  top: -5rpx;
  right: -5rpx;
  width: 30rpx;
  height: 30rpx;
  background-color: #007aff;
  border-radius: 50%;
  color: white;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid white;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}
.bottom-info {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: white;
  border-radius: 10rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.selected-info {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}
.clear-btn {
  background-color: #ff3b30;
  color: white;
  border: none;
  padding: 15rpx 30rpx;
  border-radius: 25rpx;
  font-size: 26rpx;
  box-shadow: 0 2rpx 8rpx rgba(255, 59, 48, 0.3);
}
.clear-btn:active {
  transform: scale(0.95);
}
</style>
